<template>
  <div>
    <el-form ref="form" :model="form" class="main" label-width="80px">
      <el-checkbox-group v-model="checkOptions" @change="handleCheckedSalesChange">
        <template v-for="item in options">
          <el-checkbox v-if="queryList.indexOf(item.prop) != -1" :key="item.id" :class="[checkList.includes(item.id) ? 'nameSelectActive' : 'nameSelect']" :label="item">
            <div v-if="item.type == 0" class="inputBox">
              {{ item.label }}
              <el-date-picker v-if="checkList.includes(item.id)" v-model="item.value" placeholder="选择日期"
                type="date"></el-date-picker>
            </div>
            <div v-else-if="!item.list" class="inputBox">
              {{ item.label }}
              <el-input v-if="checkList.includes(item.id)" v-model="item.value" placeholder="请输入">
              </el-input>
            </div>
            <div v-else class="inputBox">
              {{ item.label }}
              <template v-if="checkList.includes(item.id)">
                <el-select v-model="item.value" placeholder="请选择" @change="val => preventSuffix(val, item)">
                  <el-option v-for="opt in item.list" :key="opt.dictValue" :label="opt.dictLabel" :value="opt.dictValue">
                  </el-option>
                </el-select>
              </template>
            </div>
          </el-checkbox>
        </template>
      </el-checkbox-group>
      <div class="foot">
        <el-button type="text" @click="keepForm">保存为常用筛选</el-button>
        <div class="btnBox">
          <el-button plain @click="resetForm()">重置</el-button>
          <el-button type="primary" @click="submitForm()">筛选</el-button>
        </div>
      </div>
    </el-form>
  </div>
</template>
<script>
import { validateNum, validatePhone } from '@/utils/validate'
import { getPlat, getSource } from '@/api/sourceManage/sourceManage'
import { findWeGroup, getallConfig, getAllWeUser, getCanAbleFieldList } from '@/api/customer/customerManage'
import { getInsuranceType } from '@/utils/auth'

export default {
  data() {
    return {
      form: {},
      checkList: [],
      checkOptions: [],
      sourceList: [],
      options: [
        { label: '客户号', prop: 'sid', id: '1', value: '' },
        { label: '源客户号', prop: 'customerId', id: '2', value: '' },
        { label: '姓名', prop: 'name', id: '3', value: '' },
        { label: '获客平台', prop: 'customerSource', id: '4', value: '', list: [] },
        { label: '获客来源', prop: 'customerWay', id: '5', value: '', list: [] },
        { label: '微信号', prop: 'wechatNo', id: '6', value: '' },
        { label: '微信昵称', prop: 'wechatNickname', id: '7', value: '' },
        { label: '性别', prop: 'gender', id: '8', value: '', list: [] },
        { label: '婚姻状况', prop: 'marital', id: '9', value: '', list: [] },
        { label: '学历', prop: 'education', id: '10', value: '', list: [] },
        { label: '职业', prop: 'job', id: '11', value: '', list: [] },
        { label: '国籍', prop: 'nationality', id: '12', value: '', list: [] },
        { label: '年收入', prop: 'annualIncome', id: '13', value: '' },
        { label: '好友状态', prop: 'friendStatus', id: '14', value: '', list: [] },
        { label: '联系电话', prop: 'phone', id: '15', value: '' },
        { label: '保全次数', prop: 'preservationNum', id: '16', value: '' },
        { label: '报案次数', prop: 'reportNum', id: '17', value: '' },
        { label: '实际赔付次数', prop: 'actualCompenNum', id: '18', value: '' },
        { label: '有效保单数', prop: 'validPolicyNum', id: '19', value: '' },
        { label: '购买保单数', prop: 'buyPolicyNum', id: '20', value: '' },
        { label: '积分总数', prop: 'totalPoint', id: '21', value: '' },
        { label: '消费积分', prop: 'consumptionPoint', id: '22', value: '' },
        { label: '客户等级', prop: 'customerGrade', id: '23', value: '', list: [] },
        { label: '是否绑定官微', prop: 'isBindWechat', id: '24', value: '', list: [] },
        { label: '家庭总资产', prop: 'familyAssets', id: '25', value: '' },
        { label: '负债情况', prop: 'liability', id: '26', value: '' },
        { label: '配偶姓名', prop: 'spouseName', id: '27', value: '' },
        { label: '配偶客户号', prop: 'spouseCustomerId', id: '28', value: '' },
        { label: '配偶联系电话', prop: 'spousePhone', id: '29', value: '' },
        { label: '跟进阶段', prop: 'followStage', id: '30', value: '', list: [] },
        { label: '跟进人', prop: 'sysUserId', id: '31', value: '', list: [] },
        { label: '创建时间', prop: 'createTime', id: '32', value: '', type: '0' },
        { label: '企微添加人', prop: 'wecomAddUser', id: '33', value: '', list: [] },
        { label: '所属企微群聊', prop: 'wecomGroupChat', id: '34', value: '', list: [] },
        { label: '分配时间', prop: 'distributionTime', id: '35', value: '', type: '0' },
        { label: '回收时间', prop: 'recoveryTime', id: '36', value: '', type: '0' },
        // { label: "二级管理机构", prop: "secondManOrg", id: "37", value: "", list: [] },
        // { label: "三级管理机构", prop: "thirdManOrg", id: "38", value: "", list: [] },
        // { label: "四级管理机构", prop: "fourthManOrg", id: "39", value: "", list: [] },
        { label: '分配状态', prop: 'distributionState', id: '40', value: '', list: [] },
        { label: '企微添加状态', prop: 'wecomAddState', id: '41', value: '', list: [] },
        { label: '企微添加时间', prop: 'wecomAddTime', id: '42', value: '', type: '0' },
        { label: '客户状态', prop: 'customerState', id: '43', value: '', list: [] },
        { label: '备注', prop: 'remark', id: '44', value: '' },
      ],
      message: [],
      queryList: []
    }
  },
  mounted() {
    this.getOptionsList()
    this.getCanAbleFieldListFn()
  },
  methods: {
    getCanAbleFieldListFn() {
      getCanAbleFieldList().then(res => {
        if (res.code == 200) {
          this.queryList = res.data;
        }
      })
    },
    preventSuffix(val, item) {
      // console.log('val, item', val, item);
      if (item.label == '获客平台') this.getSourceList(val)
    },
    getSourceList(scrmGetGuestPlatId) {
      getSource({ scrmGetGuestPlatId }).then((res) => {
        // 获客来源
        let arr = []
        arr = res.rows.map(item => {
          return {
            dictValue: item.scrmGetGuestSourceId,
            dictLabel: item.scrmSourceName
          }
        })
        this.options.forEach(item => item.label == '获客来源' && (item.list = arr, item.value = ''))
      })
    },
    handleCheckedSalesChange(value) {

      if (value.some(item => item.label == '获客来源')) {
        !value.some(item => item.label == '获客平台') &&
          this.options.some(item => item.label == '获客平台' && this.checkOptions.push(item))
      }
      // this.message = value
      this.message = this.checkOptions
      // console.log('value', this.checkOptions);
      this.checkInputHide()
    },
    checkInputHide() {
      // 点击出现input框
      this.checkList = []
      this.checkOptions.forEach((item) => {
        this.checkList.push(item.id)
      })
    },
    submitForm() {
      if (!this.checkedInfoList(this.message)) return
      var obj = {}
      this.message.forEach(element => {
        obj[element.prop] = element.value
      })
      this.$emit('sendScreenMessage', obj)
    },
    resetForm() {
      // 重置
      this.options.forEach((item) => {
        item.value = null
      })
      this.checkOptions = []
      this.checkInputHide()
    },
    keepForm() {
      // 保存
      const searchList = this.checkOptions
      searchList.forEach((item) => {
        item.value = null
      })
      sessionStorage.setItem('searchList', JSON.stringify(searchList))
      this.resetForm()
      this.$emit('sendKeepList')
    },
    getSelectList() {
      const searchList = JSON.parse(sessionStorage.getItem('searchList')) || []
      // this.checkOptions = searchList;
      // this.checkInputHide();
    },
    checkedInfoList(message) {
      try {
        message.some((element) => {
          if (
            element.prop === 'phone' &&
            element.value &&
            !validatePhone(element.value)
          ) {
            throw new Error('请正确填写手机号！')
          }
          if (
            element.prop === 'spousePhone' &&
            element.value &&
            !validatePhone(element.value)
          ) {
            throw new Error('请正确填写手机号！')
          }
          if (
            (element.prop === 'sid' ||
              element.prop === 'customerId' ||
              element.prop === 'annualIncome' ||
              element.prop === 'familyAnnualIncome' ||
              element.prop === 'preservationNum' ||
              element.prop === 'reportNum' ||
              element.prop === 'actualCompenNum' ||
              element.prop === 'validPolicyNum' ||
              element.prop === 'buyPolicyNum' ||
              element.prop === 'totalPoint' ||
              element.prop === 'consumptionPoint' ||
              element.prop === 'familyAssets' ||
              element.prop === 'liability' ||
              element.prop === 'spouseCustomerId' ||
              element.prop === 'familyAssets' ||
              element.prop === 'liability' ||
              element.prop === 'consumptionPoint') &&
            element.value &&
            !validateNum(element.value)
          ) {
            throw new Error(`请正确填写${element.label}`)
          }
        })
        return true
      } catch (error) {
        this.$message.error(error.message)
        return false
      }
    },
    getOptionsList() {
      this.options.forEach(async item => {
        if (item.label == '性别') {
          item.list = [
            { dictValue: '0', dictLabel: '未知' },
            { dictValue: '1', dictLabel: '男' },
            { dictValue: '2', dictLabel: '女' }
          ]
        } else if (item.label == '获客来源') {
          // item.list = this.sourceList;
          // getSource().then((res) => {
          //   const arr = []
          //   res.rows.forEach(item => {
          //     arr.push(
          //       {
          //         dictValue: item.scrmGetGuestSourceId,
          //         dictLabel: item.scrmSourceName
          //       }
          //     )
          //   })
          //   item.list = arr
          // })
          // getallConfig().then(res => {
          //   item.list = res.data.map(item => {
          //     return {
          //       'dictValue': item.scrmGetGuestSourceId,
          //       'dictLabel': `${item.scrmGetGuestSourceName}(${item.scrmBussLineName}/${item.scrmGetGuestPlatName})`
          //     }
          //   })
          // })
        } else if (item.label == '获客平台') {
          getPlat({ scrmBussLineId: getInsuranceType() }).then((res) => {
            console.log(res.rows);
            const arr = []
            res.rows.forEach(item => {
              arr.push(
                {
                  dictValue: item.scrmGetGuestPlatId,
                  dictLabel: item.scrmGetGuestPlatName
                }
              )
            })
            item.list = arr
          })
          // getallConfig().then(res => {
          //   item.list = res.data.map(item => {
          //     return {
          //       'dictValue': item.scrmGetGuestPlatId,
          //       'dictLabel': `${item.scrmGetGuestPlatName}(${item.scrmBussLineName})`
          //     }
          //   })
          // })
        }
        else if (item.label == '跟进阶段') {
          this.getDicts('follow_states').then((res) => {
            if (res.code === 200) {
              item.list = res.data
            }
          })
        } else if (item.label == '跟进人' || item.label == '企微添加人') {
          // 获取跟进人列表
          const params = {
            department: '',
            userName: ''
          }
          let res = await getAllWeUser(params) || []
          if (res.code === 200) {
            const arr = []
            res.data.forEach(item => {
              arr.push(
                {
                  dictValue: item.userId,
                  dictLabel: item.userName
                }
              )
            })
            item.list = arr
          }
        } else if (item.label == '所属企微群聊') {
          // 获取所属企微群聊
          let res = await findWeGroup() || []
          if (res.code === 200) {
            const arr = []
            res.data.forEach(item => {
              arr.push(
                {
                  dictValue: item.chatId,
                  dictLabel: item.groupName
                }
              )
            })
            item.list = arr
          }
        } else if (item.label == '婚姻状况') {
          this.getDicts('marital').then((res) => {
            if (res.code === 200) {
              item.list = res.data
            }
          })
        } else if (item.label == '学历') {
          this.getDicts('education').then((res) => {
            if (res.code === 200) {
              item.list = res.data
            }
          })
        } else if (item.label == '好友状态') {
          this.getDicts('friend_status').then((res) => {
            if (res.code === 200) {
              item.list = res.data
            }
          })
        } else if (item.label == '是否绑定官微') {
          this.getDicts('is_bind_wechat').then((res) => {
            if (res.code === 200) {
              item.list = res.data
            }
          })
        } else if (item.label == '分配状态') {
          this.getDicts('distribution_state').then((res) => {
            if (res.code === 200) {
              item.list = res.data
            }
          })
        } else if (item.label == '企微添加状态') {
          this.getDicts('wecom_add_state').then((res) => {
            if (res.code === 200) {
              item.list = res.data
            }
          })
        } else if (item.label == '客户状态') {
          this.getDicts('customer_state').then((res) => {
            if (res.code === 200) {
              item.list = res.data
            }
          })
        } else if (item.label == '国籍') {
          this.getDicts('nationality').then((res) => {
            if (res.code === 200) {
              item.list = res.data
            }
          })
        } else if (item.label == '客户等级') {
          this.getDicts('customer_grade').then((res) => {
            if (res.code === 200) {
              item.list = res.data
            }
          })
        } else if (item.label == '职业') {
          this.getDicts('job_type').then((res) => {
            if (res.code === 200) {
              item.list = res.data
            }
          })
        }
      }
      )
    }
  }
}
</script>
<style lang="scss" scoped>
.main {
  padding: 0 0 110px 0;
}

.nameSelectActive {
  background: #ffefeb;
  padding: 5px 10px;
  width: 100%;
  margin: 2px 0;
  display: flex;
  align-items: center;
}

.nameSelect {
  padding: 5px 10px;
  width: 100%;
  margin: 2px 0;
  height: 42px;
  display: flex;
  align-items: center;
}

.inputBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.el-input {
  width: 70%;
}

.foot {
  position: absolute;
  bottom: 60px;
  z-index: 2;
  background: #fff;
  display: flex;
  padding: 5px 10px;
  justify-content: space-between;
  width: 100%;
}
</style>
